package com.hay.oss.obs;

import com.hay.oss.OssConstant;
import com.hay.oss.OssTemplate;
import com.hay.oss.bo.OssFile;
import com.obs.services.ObsClient;
import com.obs.services.model.ObsObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.io.InputStream;

/**
 * 文档地址 https://ecloud.10086.cn/op-help-center/doc/category/729
 * @author LiMouRen
 * @date 2023/7/26
 */
@Slf4j
public class ObsTemplate implements OssTemplate {

    private final ObsProperties obsProperties;

    private final ObsClient client;

    private final String bucketName;

    public ObsTemplate(ObsProperties obsProperties, ObsClient client){
        this.obsProperties = obsProperties;
        this.client = client;
        bucketName = obsProperties.getBucketName();
    }

    public ObsClient getClient(){
        return this.client;
    }

    /**
     * 上传文件
     * @param category 文件前缀,如 product/20240115
     * @param originalFileName 文件原名
     * @param input 流
     * @param useOriginalName true 使用原名
     */
    @Override
    public OssFile uploadFile(String category, String originalFileName, InputStream input, Boolean useOriginalName){
        String relativeUrl = createRelativeUrl(category,originalFileName,useOriginalName);
        client.putObject(bucketName, relativeUrl,  input, null);
        String link = this.getOssHost() + OssConstant.SLASH + relativeUrl;
        OssFile ossFile = new OssFile();
        ossFile.setLink(link);
        ossFile.setOriginalName(originalFileName);
        ossFile.setRelativeUrl(relativeUrl);
        return ossFile;
    }

    @Override
    public InputStream getInputStream(String relativeUrl) {
        ObsObject obsObject = getFileOss(bucketName, relativeUrl);
        Assert.notNull(obsObject,"文件不存在");
        return obsObject.getObjectContent();
    }

    /**
     * 删除文件
     * @param relativeUrl 相对地址，如 product/20240115/1.jpg
     */
    @Override
    public void removeFile(String relativeUrl){
        client.deleteObject(bucketName, relativeUrl);
    }

    /**
     * 根据文件相对路径获取文件流
     * @param relativeUrl 相对地址
     */
    public ObsObject getFileOss(String bucketName, String relativeUrl){
        return client.getObject(bucketName, relativeUrl);
    }

    /**
     * 获取主机
     * @return
     */
    public String getOssHost(){
        String host = null;
        String hostMode = obsProperties.getHostMode();
        if (OssConstant.HOST_BUCKET.equals(hostMode)){
            String prefix = this.obsProperties.getEndpoint().contains(OssConstant.HTTPS_PREFIX) ? OssConstant.HTTPS_PREFIX : OssConstant.HTTP_PREFIX;
            host =  prefix + bucketName + OssConstant.DOT + this.obsProperties.getEndpoint().replaceFirst(prefix, "");
        } else if(OssConstant.HOST_PROXY.equals(hostMode)){
            host =  obsProperties.getProxyPrefix();
        } else {
            host =  obsProperties.getEndpoint();
        }
        return host;
    }

}


